package com.va1m.mongodemo.service.impl;

import com.va1m.mongodemo.entity.User;
import com.va1m.mongodemo.mapper.UserRepository;
import com.va1m.mongodemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Admin
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserRepository userRepository;
    @Override
    public User addUser(User user) {
        //return userRepository.insert(user);
        return mongoTemplate.insert(user);
    }

    @Override
    public List<User> addUsers(List<User> users) {
//        return userRepository.insert(users);
        Collection<User> insert = mongoTemplate.insert(users, User.class);
        return insert.stream().collect(Collectors.toList());
    }

    @Override
    public void deleteUser(User user) {
        userRepository.deleteByName(user.getName());
    }


    @Override
    public void deleteUsers(List<User> users) {
        userRepository.deleteAll(users);
    }

    @Override
    public List<User> findByName(User user) {
        return mongoTemplate.find(new Query(Criteria.where("name").is(user.getName())), User.class);
    }
}
